import Taro from '@tarojs/taro'

//获取当前位置
export function getLocation(GCStype : string) {
    return new Promise((resolve, reject) => {
      Taro.getLocation({
        type: GCStype,//'wgs84',
        success: (res) => resolve(res),
        fail: (err) => reject(err)
      });
    });
  };

  interface Location {
    name: string; // 地理位置名称
    level: 'province' | 'city' | 'county'; // 地理位置级别
    parentName?: string; // 上级地理位置名称，用于构建层级关系
  }

  export function getLocationHierarchy(locationName: string, locations: Location[]): { province?: string; city?: string; county?: string } {
    const hierarchy: { province?: string; city?: string; county?: string } = {};
  
    // 遍历所有地理位置，构建层级关系
    for (const location of locations) {
      if (location.name === locationName) {
        if (location.level === 'province') {
          hierarchy.province = location.name;
        } else if (location.level === 'city') {
          hierarchy.city = location.name;
          hierarchy.province = location.parentName!; // 使用非空断言，因为我们假设数据是完整的
        } else if (location.level === 'county') {
          hierarchy.county = location.name;
          hierarchy.city = location.parentName!;
          hierarchy.province = (locations.find(l => l.name === location.parentName && l.level === 'city')?.parentName)!; // 嵌套查找省份
        }
        break; // 找到匹配项后退出循环
      }
    }
  
    return hierarchy;
  }